package com.sinoglobal.ningxia.utils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Base64;
import com.sinoglobal.ningxia.R;

/**
 * @author ty
 * @createdate 2013-4-19 上午11:54:31
 * @Description: 把drowable里的图片转换成bitmap并进行缩放处理
 */
public class BitmapUtiles {
	public static int max = 0;
	public static boolean act_bool = true;
	public static List<Bitmap> bmp = new ArrayList<Bitmap>();
	public static String model=android.os.Build.MODEL;
	// 图片sd地址 上传服务器时把图片调用下面方法压缩后 保存到临时文件夹 图片压缩后小于100KB，失真度不明显
	public static List<String> drr = new ArrayList<String>();
	public static List<String> picPathTemp = new ArrayList<String>();
	
	public static Bitmap revitionImageSize(String path) throws IOException {
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(
				new File(path)));
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(in, null, options);
		in.close();
		int i = 0;
		Bitmap bitmap = null;
		while (true) {
//			Log.i(LOGTAG,"options.outWidth"+i+" =="+options.outWidth );
//			Log.i(LOGTAG,"options.outHeight"+i+" =="+options.outHeight );

			if ((options.outWidth >> i <= 1000)
					&& (options.outHeight >> i <= 1000)) {
				in = new BufferedInputStream(
						new FileInputStream(new File(path)));
				options.inSampleSize = (int) Math.pow(2.0D, i);
				options.inJustDecodeBounds = false;
				bitmap = BitmapFactory.decodeStream(in, null, options);
				break;
			}
			i += 1;
		}
		return readPictureDegree(path,bitmap);
	}
	/**
	 * 读取图片属性：旋转的角度
	 * @param path 图片绝对路径
	 * @return degree旋转的角度
	 */
	public static Bitmap readPictureDegree(String path,Bitmap bitmap) {
		int degree  = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		/** 
		 * 把图片旋转为正的方向 
		 */  
		 return rotaingImageView(degree, bitmap);  

	}

	/*
	 * 旋转图片 
	 * @param angle 
	 * @param bitmap 
	 * @return Bitmap 
	 */  
	public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {  
		//旋转图片 动作   
		Matrix matrix = new Matrix();;  
		matrix.postRotate(angle);  
//		LogUtil.i("angle2=" + angle);  
		// 创建新的图片   
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,  
				bitmap.getWidth(), bitmap.getHeight(), matrix, true);  
		return resizedBitmap;  
	}
	public static String uploadImgForBase64(String path) throws IOException {
		Bitmap bm=revitionImageSize(path);
		ByteArrayOutputStream bao = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 100, bao);
		byte[] ba = bao.toByteArray();
		String ba1 = Base64.encodeToString(ba, 0, ba.length, Base64.DEFAULT);

		try {
			FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "bim.txt"));
			fos.write(ba1.getBytes("utf-8"));
			fos.close();
		} catch (Exception e) {
			//Auto-generated catch block
			e.printStackTrace();
		}

		return ba1;
	}
	public static Drawable scaleBitmap(Bitmap bitmapOrg, int setwh, int setht) {

		// / 加载需要操作的图片，这里是eoeAndroid的logo图片
		// Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
		// R.drawable.eoe_android);

		// 获取这个图片的宽和高
		int width = bitmapOrg.getWidth();
		int height = bitmapOrg.getHeight();

		// 定义预转换成的图片的宽度和高度
		int newWidth = setwh;
		int newHeight = setht;

		// 计算缩放率，新尺寸除原始尺寸
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();

		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);

		// 旋转图片 动作
		// matrix.postRotate(45);

		// 创建新的图片
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height, matrix, true);

		// 将上面创建的Bitmap转换成Drawable对象，使得其可以使用在ImageView, ImageButton中
		BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);

		return bmd;
	}

	public static Drawable scaleBitmap2(String path) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 4;
		Bitmap resizedBitmap = BitmapFactory.decodeFile(path, options);

		// 将上面创建的Bitmap转换成Drawable对象，使得其可以使用在ImageView, ImageButton中
		BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);

		return bmd;
	}

	/********************* Drawable转Bitmap ************************/
	public static Bitmap drawabletoBitmap(Drawable drawable) {
		int width = drawable.getIntrinsicWidth();
		int height = drawable.getIntrinsicWidth();

		Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
				: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, width, height);

		drawable.draw(canvas);

		return bitmap;
	}

	// 缩放图片
	public static Bitmap zoomImg(Bitmap bm) {
		// 获得图片的宽高
		int width = bm.getWidth();
		int height = bm.getHeight();
		int newwidth = (int) (width / 4);
		int newheight = (int) (height / 4);
		// 计算缩放率，新尺寸除原始尺寸
		float scaleWidth = ((float) newwidth) / width;
		float scaleHeight = ((float) newheight) / height;
		// 取得想要缩放的matrix参数
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		// 得到新的图片
		Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
		System.out.println(newbm.getHeight() + "------" + newbm.getWidth());
		return newbm;
	}
	/**
	 * 
	 * @author zhourihu
	 * @createdate 2013-12-12 下午1:14:18
	 * @Description: (用一句话描述该方法做什么) 裁剪bitmap 为圆形图
	 * @param bitmap
	 * @return
	 *
	 */
	public static Bitmap toRoundBitmap(Bitmap bitmap) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float roundPx;
		float left,top,right,bottom,dst_left,dst_top,dst_right,dst_bottom;
		if (width <= height) {
			roundPx = width / 2;
			top = 0;
			bottom = width;
			left = 0;
			right = width;
			height = width;
			dst_left = 0;
			dst_top = 0;
			dst_right = width;
			dst_bottom = width;
		} else {
			roundPx = height / 2;
			float clip = (width - height) / 2;
			left = clip;
			right = width - clip;
			top = 0;
			bottom = height;
			width = height;
			dst_left = 0;
			dst_top = 0;
			dst_right = height;
			dst_bottom = height;
		}

		Bitmap output = Bitmap.createBitmap(width,
				height, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect src = new Rect((int)left, (int)top, (int)right, (int)bottom);
		final Rect dst = new Rect((int)dst_left, (int)dst_top, (int)dst_right, (int)dst_bottom);
		final RectF rectF = new RectF(dst);

		paint.setAntiAlias(true);

		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, src, dst, paint);
		return output;
	}
	
	public static Bitmap getNetBitmap(String strUrl,Context context) {
//		LogUtil.e(TAG, "getBitmap from net");
		Bitmap bitmap = null;
		if(isNetworkConnected(context)){//有网络
			try {
				URL url = new URL(strUrl);
				HttpURLConnection con = (HttpURLConnection) url.openConnection();
				con.setDoInput(true);
				con.connect();
				InputStream in = con.getInputStream();
				bitmap = BitmapFactory.decodeStream(in);
				in.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally{
				
			}          
		}
		return bitmap;
	}
	
	// 判断是否连接网络
		public static boolean isNetworkConnected(Context context) {
			if (context != null) {
				ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
				if (mNetworkInfo != null) {
					return mNetworkInfo.isAvailable();
				}
			}
			return false;
		}
	/**
	 * @author sbk
	 * @createdate 2014-3-7 下午3:11:17
	 * @Description: 清除内存缓存
	 * 
	 */
	public static void clearCahe() {
		act_bool = true;
		max = 0;
		bmp.clear();
		drr.clear();
	}
	

	public static Bitmap scaleBitmapforWidth(Bitmap bitmapOrg,int newWidth){
		//图片的宽高
		int bit_Width = bitmapOrg.getWidth();
		int bit_Height = bitmapOrg.getHeight();


		//根据新的宽度计算出新的高度
		float scale = (float)bit_Width/bit_Height;
		int newHeight = (int) (newWidth/scale);
		
		// 计算缩放率，新尺寸除原始尺寸
		float scaleWidth = ((float) newWidth) / bit_Width;
				float scaleHeight = ((float) newHeight) / bit_Height;

				// 创建操作图片用的matrix对象
				Matrix matrix = new Matrix();

				// 缩放图片动作
				matrix.postScale(scaleWidth, scaleHeight);

				// 旋转图片 动作
				// matrix.postRotate(45);

				// 创建新的图片
				Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, bit_Width, bit_Height, matrix, true);
		return resizedBitmap;
	}
}